package com.qy139.sso.service.impl;


import com.qy139.entity.TabUser;
import com.qy139.sso.feign.UserService;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println("输入的用户的名字是:"+s);
        TabUser one = userService.getByName(s);
        System.out.println("用户的信息是:"+one);
        if (one == null){
            throw new RuntimeException("用户不存在！");
        }else {
            List<String> roles = userService.findRolesById(one.getId());
            List<String> menus = userService.findMenusById(one.getId());
            List<SimpleGrantedAuthority> list = new ArrayList<>();
            for (String role : roles) {
                list.add(new SimpleGrantedAuthority(role));
            }
            for (String menu : menus) {
                list.add(new SimpleGrantedAuthority(menu));
            }
            return new User(one.getName(),one.getPwd(),list);
        }
    }
}
